<?php
/**
 * User: 楚羽幽
 * Date: 19-3-28
 * Email: cyu@gzskyb.com
 */

namespace app\common\utils\manager;

class AliyunSmsManager
{

    /**
     * 发送短信
     * @param $phone
     * @param $TemplateParam
     * @param string $domain
     * @return mixed
     */
    public static function alisms($phone, $TemplateParam, $domain = 'dysmsapi.aliyuncs.com') {
        $AccessKeyId = 'LTAI4fCUyHXYjO5Y';
        $accessKeySecret = 'MmBn4ja81V7KSb0EnabiIx03hqdVzU';
        $SignName = '行铺';
        $TemplateCode = 'SMS_173160506';
        $apiParams["PhoneNumbers"] = $phone; //手机号
        $apiParams["SignName"] = $SignName; //签名
        $apiParams["TemplateCode"] = $TemplateCode; //短信模版id
        $apiParams["TemplateParam"] = json_encode($TemplateParam);  //模版内容
        $apiParams["AccessKeyId"] = $AccessKeyId; //key
        $apiParams["RegionId"] = "cn-hangzhou"; //固定参数
        $apiParams["Format"] = "json";  //返回数据类型,支持xml,json
        $apiParams["SignatureMethod"] = "HMAC-SHA1"; //固定参数
        $apiParams["SignatureVersion"] = "1.0";  //固定参数
        $apiParams["SignatureNonce"] = uniqid(); //用于请求的防重放攻击，每次请求唯一
        date_default_timezone_set("GMT"); //设置时区
        $apiParams["Timestamp"] = date('Y-m-d\TH:i:s\Z'); //格式为：yyyy-MM-dd’T’HH:mm:ss’Z’；时区为：GMT
        $apiParams["Action"] = 'SendSms'; //api命名 固定子
        $apiParams["Version"] = '2017-05-25'; //api版本 固定值

        $apiParams["Signature"] = self::computeSignature($apiParams, $accessKeySecret);  //最终生成的签名结果值

        $requestUrl = "http://". $domain . "/?";

        foreach ($apiParams as $apiParamKey => $apiParamValue) {
            $requestUrl .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
        }
        return  self::curl(substr($requestUrl, 0, -1));
    }

    /**
     * 生成最终签名
     * @param $parameters
     * @param $accessKeySecret
     * @return string
     */
    private static function computeSignature($parameters, $accessKeySecret) {
        ksort($parameters);
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . self::percentEncode($key) . '=' . self::percentEncode($value);
        }
        $stringToSign = 'GET&%2F&' . self::percentencode(substr($canonicalizedQueryString, 1));
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . "&", true)); ;

        return $signature;
    }

    /**
     * 配合签名生成
     * @param $str
     * @return mixed|string
     */
    private static function percentEncode($str) {
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    /**
     * 发起CURL-GET请求
     * @param $url
     * @return mixed
     */
    private static  function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $httpResponse=curl_exec($ch);
        if($httpResponse){
            $resutl = json_decode($httpResponse);

        }else{
            $resutl = json_decode(curl_error($ch));
        }
        curl_close($ch);
        return $resutl;
    }
}